import { Text, useMessage } from 'alemonjs'
import { validate, selects } from '@src/apps/index'
import { letters } from '@src/db/src/models/user/letters'
import { Op } from 'sequelize'
import { addIntoBag } from '@src/apps/tools/bag_update' // 引入addIntoBag函数
import { qidToUid } from '@src/apps/tools/qid_goto_uid'

export const regular = /^(!|！|\/)?领取/

const response = onResponse(selects, async e => {
  const now = Date.now()
  const [message] = useMessage(e)
  const userId = await qidToUid(e.UserId ?? e.UserKey)

  // 先将 finish_time 小于当前时间的信件 status 批量更新为 3（已过期/已删除）
  await letters.update(
    { status: 3 },
    {
      where: {
        finish_time: { [Op.lt]: now },
        status: { [Op.ne]: 3 }
      }
    }
  )

  // 查询所有未过期信件
  const letterList = await letters.findAllValues({
    where: {
      uid: userId,
      status: { [Op.ne]: 3 }
    }
  })

  const msg = e.MessageText
  const match = new RegExp('领取\\s*(\\d+)', 'i').exec(msg)
  const idx = match ? parseInt(match[1], 10) - 1 : -1
  if (!letterList.length || idx < 0 || idx >= letterList.length) {
    message.send(format(Text('\n查无此件！！！')))
    return
  }

  // 计算剩余时间
  const listWithRemain = letterList.map(l => {
    // finish_time 为 Date 类型，需转为时间戳再计算
    const finishTime = l.finish_time ? new Date(l.finish_time).getTime() : 0
    const remain = finishTime ? finishTime - now : 0
    return { ...l, remain }
  })

  // 按剩余时间升序排序
  listWithRemain.sort((a, b) => a.remain - b.remain)
  const l = listWithRemain[idx]

  // 判断things字段是否为空
  if (!l.things || l.things === '无' || l.things === '{}') {
    message.send(format(Text('\n该邮件没有附件啦！')))
    return
  }

  // 判断status字段是否为2（已领）
  if (l.status === 2) {
    message.send(format(Text('\n你已经领取过了哟！')))
    return
  }

  // 解析things字段，转为文字，并加入背包
  let thingsText = ''
  let thingsObj: any = {}

  if (typeof l.things === 'string') {
    try {
      thingsObj = JSON.parse(l.things)
    } catch {
      message.send(format(Text('\n物品数据格式有误，请联系管理员！')))
      return
    }
  } else if (typeof l.things === 'object' && l.things !== null) {
    thingsObj = l.things
  } else {
    message.send(format(Text('\n物品数据格式有误，请联系管理员！')))
    return
  }

  if (
    thingsObj &&
    typeof thingsObj === 'object' &&
    Object.keys(thingsObj).length > 0
  ) {
    thingsText = Object.entries(thingsObj)
      .map(([key, value]) => `${key}×${value}`)
      .join('，')
    for (const [key, value] of Object.entries(thingsObj)) {
      await addIntoBag(userId, key, Number(value))
    }
  } else {
    message.send(format(Text('\n该邮件没有附件啦！')))
    return
  }

  // 领取后将该邮件的status改为2（已领）
  await letters.update(
    { status: 2 },
    {
      where: {
        id: l.id
      }
    }
  )

  message.send(format(Text(`\n你领取了：${thingsText}`)))
  return
})

export default onResponse(selects, [validate, response.current])
